<template>
  <div id="forgetPasswordPage">
    <h2 class="title">梦璃若图仓 - 忘记密码</h2>
    <a-form :model="formState" name="resetPassword" autocomplete="off" @finish="handleSubmit">
      <a-form-item name="userAccount" :rules="[{ required: true, message: '请输入账号' }]">
        <a-input v-model:value="formState.userAccount" placeholder="请输入账号" />
      </a-form-item>
      <a-form-item
        name="newPassword"
        :rules="[
          { required: true, message: '请输入新密码' },
          { min: 8, message: '密码不能小于 8 位' },
        ]"
      >
        <a-input-password v-model:value="formState.newPassword" placeholder="请输入新密码" />
      </a-form-item>
      <a-form-item
        name="confirmPassword"
        :rules="[
          { required: true, message: '请确认新密码' },
          { min: 8, message: '密码长度不能小于8位' },
          {validator: validateCheckPassword},
        ]"
      >
        <a-input-password v-model:value="formState.confirmPassword" placeholder="请确认新密码" />
      </a-form-item>
      <div class="tips">
        记得密码了？
        <RouterLink to="/user/login">去登录</RouterLink>
      </div>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%" :loading="isSubmitting">
          重置密码
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">

import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { resetPassword } from '@/api/userController.ts'
import { message } from 'ant-design-vue'

const formState = reactive<API.UserConfirmPasswordRequest>({
  userAccount: '',
  newPassword: '',
  confirmPassword: '',
})

const router = useRouter()
const isSubmitting = ref(false)

const validateCheckPassword = (rule: unknown,value: string,callback: (error ?: Error)=>void) => {
  if (value && value !== formState.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  }else {
    callback()
  }
}

/**
 * 提交重置密码表单
 *
 * @param values
 */
const handleSubmit = async (values: API.UserConfirmPasswordRequest) => {
  isSubmitting.value = true
  try {
    const res = await resetPassword(values)
    if (res.data.code === 0 && res.data.data) {
      message.success('密码重置成功')
      // 重置成功后跳转到登录页面
      setTimeout(() => {
        router.push({ path: '/user/login' })
      }, 1500)
    } else {
      message.error("密码重置失败, " + (res.data.message || '请稍后重试'))
    }
  } catch (error) {
    message.error('网络错误，请稍后重试')
    console.error('重置密码失败:', error)
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
#forgetPasswordPage {
  max-width: 360px;
  margin: 0 auto;
  padding: 20px;
}

.title {
  text-align: center;
  margin-bottom: 24px;
  color: #1890ff;
}

.tips {
  margin-bottom: 16px;
  color: #bbb;
  font-size: 13px;
  text-align: right;
}

.tips a {
  color: #1890ff;
  text-decoration: none;
}

.tips a:hover {
  text-decoration: underline;
}
</style>
